import { Select, Button } from 'antd'
import { ManageGroups } from '@/desktop/components/words/library/manage-groups'
import services from '@/services'
import type { WordsGroup } from '@/services/resources/words-library'
import './WordsGroup.module.less'

export default function WordsGroupInput(props: {
  isGlobal: boolean
  value?: number | null
  onChange?: (value: number | '') => void
}) {
  const { isGlobal, value = null, onChange = () => {} } = props

  const [groups, setGroups] = useState<WordsGroup[]>([])

  const [loading, setLoading] = useState(false)
  const load = useCallback(async () => {
    setLoading(true)
    const loaded = (await services.resources.wordsLibrary.loadGroups()).filter(
      group => group.isGlobal === isGlobal,
    )
    setGroups(loaded)
    setLoading(false)
    return loaded
  }, [setGroups, isGlobal])
  useEffect(() => {
    void load()
  }, [load])

  const [managing, setManaging] = useState(false)
  const finishManage = useCallback(() => {
    setManaging(false)
    void load()
  }, [load])

  const options = [
    { value: null, label: '无分组' },
    ...groups.map(group => ({ value: group.id, label: group.name, search: group.name })),
  ]

  return <div styleName="words-group-input">
    <Select
      value={value}
      onChange={onChange}
      disabled={loading}
      options={options}
      showSearch
      optionFilterProp="search"
    />

    <Button type="link" loading={loading} onClick={() => setManaging(true)}>
      管理分组
    </Button>
    <ManageGroups isGlobal={isGlobal} open={managing} onFinish={finishManage} />
  </div>
}
